package com.evaluation.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.evaluation.common.Result;
import com.evaluation.entity.DeptEvaluatingRelation;
import com.evaluation.entity.IndicatorsPoints;
import com.evaluation.service.DeptEvaluatingRelationService;
import com.evaluation.service.IndicatorsPointsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * H5部门测评控制器
 */
@RestController
@RequestMapping("/api/h5/dept")
public class H5DeptController {

    @Autowired
    private DeptEvaluatingRelationService deptEvaluatingRelationService;

    @Autowired
    private IndicatorsPointsService indicatorsPointsService;

    /**
     * 获取待测评部门列表
     */
    @GetMapping("/pending")
    public Result<List<Map<String, Object>>> getPendingDepts(HttpServletRequest request) {
        // 从拦截器设置的属性中获取用户信息
        String jsxm = (String) request.getAttribute("currentUserName");

        if (StrUtil.isBlank(jsxm)) {
            return Result.error("用户信息异常");
        }

        try {
            List<Map<String, Object>> pendingList = deptEvaluatingRelationService.getPendingByTeacherWithIndicatorName(jsxm);
            return Result.success(pendingList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取部门列表失败");
        }
    }

    /**
     * 获取部门测评内容
     */
    @GetMapping("/content")
    public Result<List<IndicatorsPoints>> getEvaluationContent(@RequestParam Integer relationId) {
        if (relationId == null) {
            return Result.error("测评关系ID不能为空");
        }

        try {
            // 根据测评关系ID获取测评指标编号
            DeptEvaluatingRelation relation = deptEvaluatingRelationService.getById(relationId);
            if (relation == null) {
                return Result.error("测评关系不存在");
            }

            // 根据指标编号获取考核点内容
            List<IndicatorsPoints> points = indicatorsPointsService.getByZbbh(relation.getCpzbbh());

            return Result.success(points);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取测评内容失败");
        }
    }

    /**
     * 提交部门测评
     */
    @PostMapping("/submit")
    public Result<String> submitEvaluation(@RequestBody Map<String, Object> params) {
        try {
            // 安全转换relationId，支持String和Integer类型
            Object relationIdObj = params.get("relationId");
            Integer relationId = null;
            if (relationIdObj instanceof String) {
                String relationIdStr = (String) relationIdObj;
                if (StrUtil.isNotBlank(relationIdStr) && !"undefined".equals(relationIdStr) && !"null".equals(relationIdStr)) {
                    try {
                        relationId = Integer.parseInt(relationIdStr);
                    } catch (NumberFormatException e) {
                        return Result.error("测评关系ID格式错误");
                    }
                }
            } else if (relationIdObj instanceof Integer) {
                relationId = (Integer) relationIdObj;
            }
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> scores = (List<Map<String, Object>>) params.get("scores");

            if (relationId == null || CollUtil.isEmpty(scores)) {
                return Result.error("参数错误");
            }

            // 获取测评关系记录
            DeptEvaluatingRelation relation = deptEvaluatingRelationService.getById(relationId);
            if (relation == null) {
                return Result.error("测评关系不存在");
            }

            // 检查是否已经测评
            if ("1".equals(relation.getCpbs())) {
                return Result.error("该部门已完成测评");
            }

            // 构建分数数据
            int totalScore = 0;
            Integer firstScore = null, twoScore = null, threeScore = null, fourScore = null;

            for (Map<String, Object> scoreData : scores) {
                String khdbh = (String) scoreData.get("khdbh");
                // 安全转换score，支持String和Integer类型
                Object scoreObj = scoreData.get("score");
                Integer score = null;
                if (scoreObj instanceof String) {
                    String scoreStr = (String) scoreObj;
                    if (StrUtil.isNotBlank(scoreStr) && !"undefined".equals(scoreStr) && !"null".equals(scoreStr)) {
                        try {
                            score = Integer.parseInt(scoreStr);
                        } catch (NumberFormatException e) {
                            return Result.error("分数格式错误：" + scoreStr);
                        }
                    }
                } else if (scoreObj instanceof Integer) {
                    score = (Integer) scoreObj;
                } else if (scoreObj instanceof Number) {
                    score = ((Number) scoreObj).intValue();
                }
                
                if (score == null) {
                    return Result.error("分数不能为空");
                }

                // 根据考核点编号设置对应分数
                switch (khdbh) {
                    case "1":
                        firstScore = score;
                        break;
                    case "2":
                        twoScore = score;
                        break;
                    case "3":
                        threeScore = score;
                        break;
                    case "4":
                        fourScore = score;
                        break;
                }
                totalScore += score;
            }

            // 更新测评记录
            relation.setFirstscore(firstScore);
            relation.setTwoscore(twoScore);
            relation.setThreescore(threeScore);
            relation.setFourscore(fourScore);
            relation.setTotalscore(totalScore);
            relation.setCpbs("1"); // 已测评
            relation.setCpsj(DateUtil.date());

            boolean success = deptEvaluatingRelationService.updateById(relation);

            if (success) {
                return Result.success("测评提交成功");
            } else {
                return Result.error("测评提交失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统错误，请稍后重试");
        }
    }

    /**
     * 获取已测评部门列表
     */
    @GetMapping("/evaluated")
    public Result<List<Map<String, Object>>> getEvaluatedDepts(HttpServletRequest request) {
        // 从拦截器设置的属性中获取用户信息
        String jsxm = (String) request.getAttribute("currentUserName");

        if (StrUtil.isBlank(jsxm)) {
            return Result.error("用户信息异常");
        }

        try {
            List<Map<String, Object>> evaluatedList = deptEvaluatingRelationService.getEvaluatedByTeacherWithIndicatorName(jsxm);
            return Result.success(evaluatedList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取已测评部门列表失败");
        }
    }

    /**
     * 查看已测评部门详情
     */
    @GetMapping("/evaluated/detail")
    public Result<Map<String, Object>> getEvaluatedDetail(@RequestParam Integer relationId) {
        if (relationId == null) {
            return Result.error("测评关系ID不能为空");
        }

        try {
            // 获取测评关系记录
            DeptEvaluatingRelation relation = deptEvaluatingRelationService.getById(relationId);
            if (relation == null) {
                return Result.error("测评关系不存在");
            }

            // 获取考核点内容
            List<IndicatorsPoints> points = indicatorsPointsService.getByZbbh(relation.getCpzbbh());

            // 构建返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("relation", relation);
            result.put("points", points);

            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取测评详情失败");
        }
    }
}
